<template>
  <div class="form-page">
    <div class="block-wrap form-container">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="8em"
        v-loading="fromLoading"
      >
        <el-form-item label="角色名称" prop="sysRole.roleName">
          <el-input
            v-model="form.sysRole.roleName"
            placeholder="长度为5~20个字符，只能包含汉字、字母、数字"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="配置权限:"
          class="authority"
          prop="sysRole.menuIds"
        >
          <el-tree
            :data="dataList"
            :props="customProps"
            show-checkbox
            :default-expand-all="true"
            :default-checked-keys="form.menuIds"
            node-key="id"
            ref="jurisdictionTree"
            :render-content="renderContent"
            @node-expand="handleNodeExpand"
          >
          </el-tree>
        </el-form-item>
        <el-form-item label="所属机构:" prop="sysRole.deptId">
          <el-select
            v-model="form.sysRole.deptId"
            @change="handeleDept"
            placeholder="请选择所属机构"
          >
            <el-option
              v-for="item in deptList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择管理员:">
          <el-select
            v-model="form.users"
            multiple
            @change="handeleUsers"
            value-key="userId"
          >
            <el-option
              v-for="item in manageList"
              :key="item.userId"
              :label="item.username"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            v-model="form.sysRole.roleDesc"
            type="textarea"
            :autosize="{ minRows: 2 }"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitForm"
            >提交</el-button
          >
          <el-button type="default" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
      <div class="subImg">
        <img src="@/assets/roleSub.png" alt="" />
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogTableVisible"
      width="560px"
      :show-close="false"
      top="25vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-result icon="success" title="创建用户成功">
        <template slot="extra">
          <el-button type="primary" size="medium" @click="continueAdd"
            >继续创建</el-button
          >
          <el-button size="medium" @click="gotoManaList">返回列表</el-button>
        </template>
      </el-result>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMenuList,
  getDeptFindAll,
  getAllUser,
  addRole,
  updateRole,
  getRoleInfo
} from "@/api/sys";
export default {
  name: "AddMenu",
  data() {
    return {
      passwordType: "password",
      passwordReType: "password",
      form: {
        sysRole: {
          roleName: "",
          roleDesc: "",
          deptId: ""
        },
        users: [],
        menuIds: []
      },
      rules: {
        "sysRole.roleName": [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "长度在 5 到 20 个字符",
            trigger: "blur"
          },
          {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/,
            message: "请勿输入特殊字符",
            trigger: "blur"
          }
        ],
        "sysRole.deptId": [
          { required: true, message: "请选择机构", trigger: "blur" }
        ]
      },
      dataList: [],
      customProps: {
        label: "name",
        children: "children"
      },
      manageList: [],
      deptList: [],
      fromLoading: false,
      dialogTableVisible: false,
      loading: false
    };
  },
  watch: {
    $route: {
      handler() {
        let { roleId } = this.$route.query;
        if (roleId) {
          this.$route.meta.title = "编辑角色";
          this.getRoleInfo(roleId);
        } else {
          this.$route.meta.title = "新增角色";
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getMenuList();
    this.getDeptFindAll();
  },
  mounted() {},
  methods: {
    getMenuList() {
      this.fromLoading = true;
      getMenuList()
        .then(res => {
          this.dataList = res.data;
          this.changeCss();
          this.fromLoading = false;
        })
        .catch(() => {
          this.fromLoading = false;
        })
        .finally(() => {
          this.fromLoading = false;
        });
    },
    async getAllUser(deptId) {
      let data = await getAllUser(deptId);
      this.manageList = data.data;
    },
    handeleDept(value) {
      this.form.users = [];
      this.getAllUser({ deptId: value });
    },
    async getRoleInfo(roleId) {
      let res = await getRoleInfo(roleId);
      let { sysRole, users, menuIds } = res.data;
      this.form.sysRole = sysRole;
      this.form.sysRole.deptId = sysRole.deptId.toString();
      let data = await getAllUser({ deptId: this.form.sysRole.deptId });
      this.manageList = data.data;
      this.form.users = users;
      this.form.menuIds = menuIds;
    },
    getDeptFindAll() {
      getDeptFindAll().then(res => {
        this.deptList = res.data;
      });
    },
    handeleUsers(item) {},
    submitForm() {
      console.log(this.form.menuIds);
      this.form.menuIds = this.$refs.jurisdictionTree.getCheckedKeys();
      this.loading = true;
      if (this.form.menuIds.length === 0) {
        this.$message.error("请给角色配置权限！");
        this.loading = false;
      } else {
        this.$refs.form.validate(valid => {
          if (valid) {
            let { roleId } = this.$route.query;
            if (!roleId) {
              this.addUser();
            } else {
              this.editUser();
            }
          } else {
            console.log("error submit!!");
            this.loading = false;
            return false;
          }
        });
      }
    },
    addUser() {
      addRole(this.form)
        .then(res => {
          if (res.code === 200) {
            this.dialogTableVisible = true;
          }
        })
        .catch(err => {
          this.loading = false;
        });
    },
    editUser() {
      updateRole(this.form)
        .then(res => {
          if (res.code === 200) {
            this.$message.success("更新成功");
            this.loading = false;
            this.$router.push({ name: "Role" });
          }
        })
        .catch(err => {
          this.loading = false;
        });
    },
    // 修改树形结构最后一层
    renderContent(h, { node, data, store }) {
      let classname = "";
      if (node.childNodes.length === 0) {
        classname = "floatRight";
      } else if (node.childNodes.length > 0) {
        classname = "clearFloat";
      }
      return <span class={classname}>{node.label}</span>;
    },
    handleNodeExpand() {
      this.changeCss();
    },
    changeCss() {
      this.$nextTick(() => {
        var levelName = document.getElementsByClassName("floatRight");
        for (var i = 0; i < levelName.length; i++) {
          let parentNode = levelName[i].parentNode;
          parentNode.style.cssFloat = "left";
          parentNode.style.styleFloat = "left";
        }
        // var clearFloat = document.getElementsByClassName("clearFloat");
        // for (var i = 0; i < clearFloat.length; i++) {
        //   let parentNode = clearFloat[i].parentNode;
        //   parentNode.style.clear = "both";
        //   parentNode.style.clear = "both";
        // }
      });
    },
    cancel() {
      this.$router.go(-1);
    },
    continueAdd() {
      this.loading = false;
      this.dialogTableVisible = false;
      this.form = {
        deptId: "",
        username: "",
        password: "",
        newpassword1: "",
        realName: "",
        phone: "",
        role: [],
        remark: ""
      };
    },
    gotoManaList() {
      this.loading = false;
      this.dialogTableVisible = false;
      this.$router.push({ name: "Role" });
    }
  }
};
</script>

<style lang="scss">
@import "~@/styles/page/form-page.scss";
</style>
<style lang="scss" scoped>
.form-page {
  .form-container {
    margin-bottom: 0;
    padding: 0;
    overflow: hidden;
    .el-form {
      float: left;
      width: 760px;
      margin-left: 182px;
      margin-top: 69px;
      .authority {
        margin-bottom: 0;
        .el-tree {
          padding-top: 20px;
          margin-bottom: 10px;
        }
        ::v-deep.el-form-item__label::before {
          content: "*";
          color: #ff4d4f;
          margin-right: 4px;
        }
      }
      .el-button--primary {
        background-color: #1890ff;
        border-color: #1890ff;
      }
    }
    .subImg {
      float: left;
      margin-left: 225px;
      margin-top: 168px;
    }
    ::v-deep.el-dialog {
      .el-dialog__header {
        display: none;
      }
      .el-dialog__body {
        padding: 0;
      }
    }
    .el-button.el-button--primary.el-button--medium {
      background-color: #1890ff;
      border-color: #1890ff;
    }
  }
  ::v-deep.el-dialog {
    .el-dialog__header {
      display: none;
    }
    .el-dialog__body {
      padding: 0;
    }
  }
  .el-button.el-button--primary.el-button--medium {
    background-color: #1890ff;
    border-color: #1890ff;
  }
}
.block-wrap {
  padding: 25px;
  background: #fff;
  border-radius: 2px;
  ::v-deep.el-tree-node__content {
    height: 36px;
  }
}
</style>
